
const { init } = require('./../../wxCloudClientSDK.umd.js')
// 指定云开发环境 ID
wx.cloud.init({
  env: "cloud1-9gel6ndh8e555155", // 当前的云开发环境 ID
});

const client = init(wx.cloud);

Page({
  data: {
    memberInfo: {},
    currentLevel: '',
    currentMember: null
  },

  onLoad(options) {
    const id = options.id || '';
    
    /*
    this.setData({
      currentLevel: level,
      currentMember: this.data.memberInfo[level]
    });
    */
    // 设置导航栏标题
    /*
    wx.setNavigationBarTitle({
      title: '会员卡详情'
    });
    */

    this.queryMembershipInfo(id);
  },

  queryMembershipInfo: function(id) {
    
    client.models.membership_levels.get({
      filter: {
        where: {
          $and: [{
            _id: {
              $eq: id,
            }
          }]
        }
      }
    }).then(res => {
      this.parseMembershipInfo(res.data);
    }).catch(res => {
      console.log("query membership_level err: ", res);
    });

  },

  // 解析会员级别信息
  parseMembershipInfo: function(data) {

    this.setData({
      memberInfo: {
      name: data.levelName,
      cardImage: data.cardImageUrl,
      benefits: data.benefits,
      price: data.price,
      duration: data.duration,
      durationUnit: data.durationUnit,
      description: data.description,
    },
  });

  },

  // 处理充值
  handleRecharge() {
    const memberInfo = this.data.currentMember;
    wx.showModal({
      title: '确认充值',
      content: `确认购买${memberInfo.name}？费用：¥${memberInfo.price}/${memberInfo.duration}个月`,
      success: (res) => {
        if (res.confirm) {
          this.processPayment();
        }
      }
    });
  },

  // 处理支付流程
  processPayment() {
    wx.showLoading({
      title: '正在处理',
    });

    // 调用支付接口
    wx.requestPayment({
      timeStamp: '',
      nonceStr: '',
      package: '',
      signType: 'MD5',
      paySign: '',
      success: (res) => {
        wx.hideLoading();
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000,
          success: () => {
            // 支付成功后的处理
            setTimeout(() => {
              wx.navigateBack();
            }, 2000);
          }
        });
      },
      fail: (err) => {
        wx.hideLoading();
        wx.showToast({
          title: '支付失败',
          icon: 'none'
        });
      }
    });
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  }
}); 